package pers.qianyu.month_202103.date_20210316;

import org.junit.Test;

import java.util.Arrays;

/**
 * 59. 螺旋矩阵 II
 * https://leetcode-cn.com/problems/spiral-matrix-ii/
 *
 * @author mizzle_rain
 * @since 2021年3月16日 15点07分
 */
public class GenerateMatrix {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int[][] dxy = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        for (int i = 1, x = 0, y = 0, t = 0; i <= n * n; i++, x += dxy[t][0], y += dxy[t][1]) {
            res[x][y] = i;
            int a = x + dxy[t][0], b = y + dxy[t][1];
            if (a < 0 || b < 0 || a >= n || b >= n || res[a][b] != 0) {
                t = (t + 1) % 4;
            }
        }
        return res;
    }

    @Test
    public void test1() {
        System.out.println(Arrays.deepToString(new GenerateMatrix().generateMatrix(3)));
    }
}
